package com.cjh.handler;

import com.cjh.constant.JwtConstant;
import com.cjh.utils.ResponseUtil;
import com.cjh.utils.ResultJson;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * 认证失败处理器
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //处理异常
        //请求uri
        String requestURI = httpServletRequest.getRequestURI();
        if (Objects.equals(requestURI,"/user/login")){
            ResponseUtil.returnJson(httpServletResponse, ResultJson.fail(401,"用户名或密码错误"));
        }else{
            if (Objects.isNull(httpServletRequest.getHeader(JwtConstant.AUTHORIZATION))) {
                ResponseUtil.returnJson(httpServletResponse, ResultJson.fail(401, "缺少Authorization参数"));
            }
        }

    }
}
